package com.bw.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.permission.entity.Menu;
import com.bw.permission.entity.RoleMenu;
import com.bw.permission.entity.User;
import com.bw.permission.entity.UserRole;
import com.bw.permission.mapper.MenuMapper;
import com.bw.permission.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.permission.utils.JwtUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhanggm
 * @since 2020-10-28
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IRoleMenuService iRoleMenuService;
    
    @Autowired
    private IMenuService iMenuService;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public List<Menu> getMenuTreeByUsername(String username) {
        List<Menu> menuList = null;
        //管理员查询所有菜单
        if("admin".equals(username)){
            menuList = iMenuService.list();
        }else {
            //非管理员查询菜单
            menuList = getMenuListByUsername(username);
        }
        //查询一级菜单
        List<Menu> treeMenuList = getMenuListByPid(0,menuList);
        //把菜单封装成tree
        getSubMenu(treeMenuList,menuList);
        return treeMenuList;
    }

    @Override
    public PageInfo<Menu> getPageInfo(Menu menu, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        if(menu.getParentId()!=null){
            queryWrapper.eq("parentId",menu.getParentId());
        }
        if(menu.getName()!=null){
            queryWrapper.like("name",menu.getName());
        }
        List<Menu> list = list(queryWrapper);
        //设置所属菜单名称
        list.forEach(m->{
            if(m.getParentId()>0){
                Menu byId = iMenuService.getById(m.getParentId());
                m.setParentName(byId.getName());
            }
        });
        return new PageInfo<>(list);
    }

    /**
     * 根据登录名称，查询菜单
     * @param username
     * @return
     */
    public List<Menu> getMenuListByUsername(String username){
        String curUsername = jwtUtils.getCurUsername();
        //根据用户名称查询用户
        User user = iUserService.getByUsername(curUsername);
        //根据用户Id查询角色Ids
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("uid",user.getId());
        List<UserRole> userRoleList = iUserRoleService.list(queryWrapper);
        List<Integer> roleIds = userRoleList.stream().map(ur -> ur.getRid()).collect(Collectors.toList());
        //根据角色Ids，查询菜单ids
        queryWrapper.clear();
        queryWrapper.in("rid",roleIds);
        List<RoleMenu> roleMenuList = iRoleMenuService.list(queryWrapper);
        List<Integer> menuIds = roleMenuList.stream().map(rm -> rm.getMid()).collect(Collectors.toList());
        //根据菜单ids，查询菜单
        List<Menu> menuList = iMenuService.listByIds(menuIds);
        return menuList;
    }

    /**
     * 根据pid查询菜单
     * @param pid
     * @param allMenuList
     * @return
     */
    @Override
    public List<Menu> getMenuListByPid(Integer pid,List<Menu> allMenuList){
        List<Menu> menuList = new ArrayList<>();
        allMenuList.forEach(menu -> {
            if(menu.getParentId().intValue()==pid.intValue()){
                menuList.add(menu);
            }
        });
       // List<Menu> mList = allMenuList.stream().filter(menu -> menu.getParentId().equals(pid)).collect(Collectors.toList());
        return menuList;
    }

    /**
     * 递归查询子菜单
     * @param menus
     * @param allMenus
     */
    public void getSubMenu(List<Menu> menus,List<Menu> allMenus){
        menus.forEach(menu -> {
            List<Menu> subMenuList = getMenuListByPid(menu.getId(), allMenus);
            if(subMenuList!=null){
                menu.setSubMenu(subMenuList);
                subMenuList.forEach(subMenu->{
                    getSubMenu(subMenuList,allMenus);
                });
            }
        });
    }

}
